package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.business.dto.ModularizationdDTO;
import com.yuanfeng.business.dto.PersonMessageInfoDTO;
import com.yuanfeng.business.dto.ShopBaseDTO;
import com.yuanfeng.business.entity.*;
import com.yuanfeng.business.feign.BaseServiceClient;
import com.yuanfeng.business.feign.ThirdPartyServiceClient;
import com.yuanfeng.business.feign.UsermsServiceClient;
import com.yuanfeng.business.mapper.ShopBaseMapper;
import com.yuanfeng.business.mapper.ShopCashOnDeliveryMapper;
import com.yuanfeng.business.mapper.ShopJoinBaseMapper;
import com.yuanfeng.business.mapper.ShopJoinPayMapper;
import com.yuanfeng.business.service.ShopClassBindService;
import com.yuanfeng.business.service.ShopJoinPayService;
import com.yuanfeng.business.vo.ShopPayInfoVO;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ShopJoinPayServiceImpl
 * @Description 支付凭证
 * @Author cf
 * @Date 2023/6/21 11:44
 * @Version 1.0
 */
@Service
public class ShopJoinPayServiceImpl extends ServiceImpl<ShopJoinPayMapper, ShopJoinPayEntity> implements ShopJoinPayService {

    private final static Logger log = LoggerFactory.getLogger(ShopJoinPayServiceImpl.class);

    @Autowired
    private ShopJoinPayMapper shopJoinPayMapper;

    @Autowired
    private ShopBaseMapper shopBaseMapper;

    @Autowired
    private ShopJoinBaseMapper shopJoinBaseMapper;

    @Autowired
    private ShopCashOnDeliveryMapper shopCashOnDeliveryMapper;

    @Autowired
    private UsermsServiceClient usermsServiceClient;

    @Autowired
    private ShopClassBindService shopClassBindService;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Override
    public ResponseResult uploadPayEvidence(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        try{
            String token = param.get("token").toString();
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            String userId = userInfo.getUserId().toString();
            param.put("userId",userId);
            shopJoinPayMapper.updateShopJoinPay(param);
            rr.setCode(CommonStatusEnum.SUCCESS.getCode());
            rr.setMessage(BizCodeEnume.UPLOAD_SUCCESS.getMsg());
        }catch(Exception e){
            log.error(e.getMessage());
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.UPLOAD_ERROR.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult auditShopJoinPay(Map<String, Object> param) {
        ResponseResult responseResult;
        Integer auditStatus = (Integer) param.get("auditStatus");
        String joinId;
        try {
            ShopJoinPayEntity shopJoinPay = ParseMapUtils.parseMap2Object(param, ShopJoinPayEntity.class);
            shopJoinPay.setLastUpdateTime(DateUtils.getNowDate());
            this.baseMapper.update(null, new LambdaUpdateWrapper<ShopJoinPayEntity>()
                    .set(ShopJoinPayEntity::getAuditStatus,shopJoinPay.getAuditStatus())
                    .set(ShopJoinPayEntity::getAuditComment,shopJoinPay.getAuditComment())
                    .eq(ShopJoinPayEntity::getPayId, param.get("payId")));
            //审核通过 插入shop_base表
            ShopBaseDTO shopBaseReqEntity = shopBaseMapper.queryForShopBase((Integer) param.get("payId"));
            //查询用户手机号
            String phone = shopBaseMapper.selectuserphone(shopBaseReqEntity.getUserId());
            //发送手机短信通知
            Map smsMap = new HashMap<String,Object>();
            smsMap.put("userMobile",phone);
            smsMap.put("smstype",2);
            String content = "";
            //审核通过 插入shop_base表
            if (CommonType.JoinPayStatus.AUDIT_SUCCESS.getCode().equals(auditStatus)) {
                PersonMessageInfoDTO paramTmp = new PersonMessageInfoDTO();
                //查找商家入驻的 账号,名称,地址,joinId,店铺名,店铺类型,绑定分类
                ShopBaseDTO shopBaseDTO = this.baseMapper.queryForShopBase((Integer) param.get("payId"));
                Map<String, String> vo = new HashMap<>();
                vo.put("userId",shopBaseDTO.getUserId());
               ResponseResult uiStr = usermsServiceClient.queryUserInfoByUserInfoVO(vo);
               UserInfoVO ui = JSON.parseObject(JSON.toJSONString(uiStr.getData()), UserInfoVO.class);
                ShopBaseEntity shopBase = shopBaseMapper.selectOne(new LambdaQueryWrapper<ShopBaseEntity>()
                        .eq(ShopBaseEntity::getUserId, shopBaseDTO.getUserId()));
                Integer shopId = shopBase == null ? null : shopBase.getShopId();
                joinId = shopBaseDTO.getJoinId();
                //查找商家默认LOGO
                String rr = baseServiceClient.selectConfigValueFeign(CommonType.configKey.SHOP_LOGO_WRITING.getDesc());
                //设置商家信息 为后续添加商家做准备
                paramTmp.setShopLogo(rr);
                paramTmp.setShopStatus(CommonType.storeStatus.SUCCESSFULLY.getCode());
                paramTmp.setShopSelfSupport("false");
                paramTmp.setDistrictId(shopBaseDTO.getDistrictId());
                paramTmp.setUserId(shopBaseDTO.getUserId());
                paramTmp.setUserName(shopBaseDTO.getUserName());
                paramTmp.setShopName(shopBaseDTO.getShopName());
                paramTmp.setShopType(CommonType.JoinType.BUSINESS_SHOP.getCode());
                paramTmp.setShopBusiness(shopBaseDTO.getShopType());
                paramTmp.setShopClassId(shopBaseDTO.getShopClass());
                paramTmp.setPaymentVerifyStatus(CommonType.VerifyStatus.AUDIT_SUCCESS.getCode());
                if (null != shopBaseDTO.getShopType() && CommonType.ShopType.SUPPLY_SHOP.getCode().equals(shopBaseDTO.getShopType())) {
                    paramTmp.setShopType(CommonType.JoinType.SUPPLY_SHOP.getCode());
                    paramTmp.setShopBusiness(CommonType.ShopBusiness.SUPPLIER.getCode());
                }
                if (CommonType.JoinType.BUSINESS_SHOP.getCode().equals(shopBaseDTO.getShopType())) {
                    //查找商家入驻的基本信息
                    ShopJoinBaseEntity joinBase = shopJoinBaseMapper.selectOne(new QueryWrapper<ShopJoinBaseEntity>().eq("user_id", ui.getUserId()));
                    //企业基本信息
                    Map<String, String> map = new HashMap<>();
                    map.put("userId", shopBaseDTO.getUserId());
                    map.put("taxId", joinBase.getTaxId());
                    map.put("companyName", joinBase.getEnterpriseName());
                    map.put("businessLicense", joinBase.getBusinessLicencePic());
                    map.put("registeredAddress", joinBase.getBlAddress());
                    map.put("contactNumber", joinBase.getEnterprisePhone());
                    map.put("token",param.get("token").toString());

                    if (CommonType.commonStatus.NO.getCode().equals(ui.getIsBusiness())) {
                        //添加企业
                        responseResult = usermsServiceClient.insertBusiness(map);
                    } else {
                        //修改企业
                        responseResult = usermsServiceClient.updateBusinessInfo(map);
                    }
                    if (responseResult.getCode() != 1) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚事务
                        return ResponseResult.fail(BizCodeEnume.AUDIT_ERROR.getCode(), BizCodeEnume.AUDIT_ERROR.getMsg());
                    }
                }

                //设置发票管理默认开启
                if (shopBaseDTO.getShopType() == 3) {
                    paramTmp.setInvoiceSwitchStatus(1);
                    paramTmp.setInvoiceAuditStatus(1);
                    paramTmp.setShopType(3);
                    paramTmp.setShopBusiness(4);
                }
                if (null == shopId) {
                    //添加店铺信息
                    Map<String, Object> map=ParseMapUtils.beanToMap(paramTmp);
                    map.put("shopId",null);
                    shopBaseMapper.insertShopBase(map);
                    shopId = Integer.valueOf(String.valueOf(map.get("shopId")));
                    Map<String, Object> paraMap = new HashMap<>();
                    paraMap.put("sellerName", paramTmp.getUserName());
                    paraMap.put("shopId", shopId.toString());
                    paraMap.put("userId", paramTmp.getUserId());
                    paraMap.put("shopType", paramTmp.getShopType());
                    paraMap.put("sellerLoginTime", DateUtils.getNowDate());
                    //注册商户
                    ResponseResult resp = usermsServiceClient.addSeller(paraMap);
                    //注册失败
                    if (resp.getCode() != 1) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚事务
                        return resp;
                    }
                    //更新入驻绑定的店铺id
                    shopClassBindService.update(new LambdaUpdateWrapper<ShopClassBindEntity>()
                            .set(ShopClassBindEntity::getShopId, shopId)
                            .eq(ShopClassBindEntity::getJoinId, joinId));


                    //品牌店铺入驻默认开启货到付款和发票管理
                    if (shopBaseDTO.getShopType() == 3){
                        ShopCashOnDeliveryEntity applyPayOnDeliveryRecordDTO = new ShopCashOnDeliveryEntity();
                        applyPayOnDeliveryRecordDTO.setShopId(Integer.valueOf(shopId));
                        applyPayOnDeliveryRecordDTO.setUserId(shopBaseDTO.getUserId());
                        applyPayOnDeliveryRecordDTO.setApplyStatus(2);
                        applyPayOnDeliveryRecordDTO.setReason("默认开启");
                        applyPayOnDeliveryRecordDTO.setShopName(shopBaseDTO.getShopName());
                        shopCashOnDeliveryMapper.insert(applyPayOnDeliveryRecordDTO);

                        //底部导航插入
                        ModularizationdDTO modular = new ModularizationdDTO();
                        modular.setShopId(shopId);
                        modular.setPageType(1);
                        modular.setPageStart(1);
                        modular.setPageIsIndex(3);
                        String UUidPageId= UUIDUtil.getUUID1();
                        modular.setPageId(Integer.valueOf(UUidPageId.substring(0,7)));
                        modular.setPageData("{\"color\":\"#E11A1A\",\"items\":[{\"navTitle\":\"首页\",\"navUrlSign\":\"首页\"," +
                                "\"navUrl\":\"\",\"navIndex\":0,\"icon\":\"home_s1\"},{\"navTitle\":\"我的\",\"navUrlSign\":\"用户中心\"," +
                                "\"navUrl\":\"\",\"navIndex\":3,\"icon\":\"user_s1\"},{\"icon\":\"cart_s1\"," +
                                "\"navTitle\":\"购物车\",\"navUrlSign\":\"购物车\",\"navUrl\":\"\",\"navIndex\":2}]}");
                        this.baseMapper.add(modular);


                        //移动端广告图
                        String config_key = "wep_me_page_advertising_" + shopId;
                        //注册隐私协议
                        String config_key1 = "registration_page_" + shopId;
                        //个人注册协议
                        String config_key2 = "registration_user_" + shopId;
                        //登录logo
                        String config_key3 = "logo_copywriting_ico_h5_registr_" + shopId;
                        ArrayList<String> list = new ArrayList<>();
                        list.add(config_key);
                        list.add(config_key1);
                        list.add(config_key2);
                        list.add(config_key3);
                        List<String> configKey = this.baseMapper.queryConfigKey(list);
                        if (configKey != null && configKey.size() < 3) {
                            ArrayList<String> list1 = new ArrayList<>();
                            if(!configKey.contains(config_key)){
                                list1.add(config_key);
                            }
                            if(!configKey.contains(config_key1)){
                                list1.add(config_key1);
                            }
                            if(!configKey.contains(config_key2)){
                                list1.add(config_key2);
                            }
                            if(!configKey.contains(config_key3)){
                                list1.add(config_key3);
                            }
                            this.baseMapper.insertConfigKey(list1);
                        }

                    }




                } else {
                    //更新店铺信息
                    paramTmp.setShopId(shopId);
                    shopBaseMapper.updateShopBase(paramTmp);
                }
//                //保存店铺质保金相关信息
//                if(null!=paramTmp.getShopId()){
//                    ShopRetentionMoneyEntity entity=new ShopRetentionMoneyEntity();
//                    entity.setShopId(paramTmp.getShopId());
//                    shopRetentionMoneyService.save(entity);
//                }
                smsMap.put("result1","恭喜");
                smsMap.put("result2","审核已通过，祝您开店旅途愉快~");
                //发送站内信
                content = "审核已通过，祝您开店旅途愉快~";
            }else{
                smsMap.put("result1","很抱歉");
                smsMap.put("result2","由于" + param.get("auditComment")  + "原因审核失败，请登录网站查看");
                //发送站内信
                content = "很抱歉由于" + param.get("auditComment")  + "原因审核失败，请登录网站查看";
            }
            this.shopBaseMapper.insertSysMessage("",shopBaseReqEntity.getUserId(),shopBaseReqEntity.getUserName(),5,
                    "店铺入驻资质审核",content, "");
            thirdPartyServiceClient.storeQualification(smsMap);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(BizCodeEnume.AUDIT_ERROR.getCode(), BizCodeEnume.AUDIT_ERROR.getMsg());
        }
    }

    @Override
    public ResponseResult queryShopPayDetail(Map<String, Object> param) {
        QueryWrapper queryWrapper = new QueryWrapper<>().eq("pay_id", param.get("payId"));
        ShopJoinPayEntity res = this.baseMapper.selectOne(queryWrapper);
        return ResponseResult.success(res);
    }

    @Override
    public ResponseResult queryShopPayList(Map<String, Object> param) {
        try {
            Page<ShopPayInfoVO> page = new Page<>((Integer) param.get("page"), (Integer) param.get("limit"));
            IPage<ShopPayInfoVO> results = this.baseMapper.queryShopPayPage(page, param);
            return ResponseResult.success(PageUtils.getPage(results));
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(BizCodeEnume.QUERY_ERROR.getCode(), BizCodeEnume.QUERY_ERROR.getMsg());
        }
    }

    @Override
    public ResponseResult pendingprocessing() {
        //查询待审核上架商品
        Map<String, Object> map = this.baseMapper.selectcount();

        return ResponseResult.success(map);
    }

}
